package cn.tjd.jwttest.config.mvc;

import cn.tjd.jwttest.config.anno.PassToken;
import cn.tjd.jwttest.utils.TokenUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

public class UserInterceptor implements HandlerInterceptor {

    /**
     * 用于缓存当前线程中Token保存的信息
     */
    private static final ThreadLocal<Map> cache = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //PassToken，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            return true;
        }
        if (token == null) {
            response.setHeader("content-Type", "text/html;charset=UTF-8");
            response.getWriter().write("登录过期");
            return false;
        }
        Claims claims = TokenUtils.parseJWT(token);
        cache.set(claims);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        cache.remove();
    }

    public static Map<String,String> getUser() {
        return cache.get();
    }
}
